package com.cyandpos.pad.sale.adapter;

import android.app.AlertDialog;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cyandpos.pad.R;
import com.cyandpos.pad.activity.MainActivity;
import com.cyandpos.pad.activity.MorefunctionActivity;
import com.cyandpos.pad.common.ManagerCardManager.MangerCardData;
import com.cyandpos.pad.common.commondata.ConstantString;
import com.cyandpos.pad.common.commondata.DialogConstant;
import com.cyandpos.pad.common.commondata.OnDialogListener;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.QueryGoodParam;
import com.cyandpos.pad.sale.saleutils.SaleUtil;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PermissionsUtils;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;

import java.text.DecimalFormat;
import java.util.List;

public class GoodsListAdapter extends BaseQuickAdapter<Goods, BaseViewHolder> {
    public MainActivity activity;
    private String content;
    private AlertDialog mDialog;

    public GoodsListAdapter(int layoutResId, @Nullable List<Goods> data, MainActivity activity) {
        super(layoutResId, data);
        this.activity = activity;
    }

    @Override
    protected void convert(BaseViewHolder baseViewHolder,final Goods goods) {
        LinearLayout llGoodInfo = baseViewHolder.getView(R.id.ll_item_goodInfo);
        TextView tvInx = baseViewHolder.getView(R.id.tv_sale_good_ticket_inx);
        TextView tvCode = baseViewHolder.getView(R.id.tv_sale_good_code);
        TextView tvName = baseViewHolder.getView(R.id.tv_sale_good_name);
        TextView tvPrice = baseViewHolder.getView(R.id.tv_sale_good_price);
//        final EditText etCount = baseViewHolder.getView(R.id.et_sale_goods_salecount);
        final TextView tvCount = baseViewHolder.getView(R.id.tv_sale_goods_salecount);
        TextView tvDiscount = baseViewHolder.getView(R.id.tv_sale_good_discountMoney);
        TextView tvSaleMoney = baseViewHolder.getView(R.id.tv_sale_good_saleMoney);
        ImageView imgAdd = baseViewHolder.getView(R.id.img_sale_goods_add);
        ImageView imgCut = baseViewHolder.getView(R.id.img_sale_goods_cut);
        ImageView btnDelete = baseViewHolder.getView(R.id.img_sale_goods_delect);
        ImageView btnDiscount = baseViewHolder.getView(R.id.img_sale_goods_discountFun);

        int ticktGoodsInx =1;
        int ticktInx =1;
        if(goods.getTicktGoodsInx()!=null && goods.getTicktInx()!=null){
            ticktGoodsInx = Integer.parseInt(goods.getTicktGoodsInx());
            ticktInx = Integer.parseInt(goods.getTicktInx());
        }
        tvInx.setText((ticktGoodsInx+1)+"/"+(ticktInx+1));
        tvCode.setText("【"+goods.getCode()+"】");
        tvName.setText(goods.getName());
        tvPrice.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getPrice())));
        tvCount.setText(goods.getSaleCount());   //显示数量
        tvDiscount.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getDiscount())));//折扣
        tvSaleMoney.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney()) - MoneyUtils.getMoneyInt((goods.getDiscount()))));



        View.OnClickListener itemListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.img_sale_goods_add:  //加商品
                        Double goodCountAdd = Double.valueOf(goods.getSaleCount())+1;
//                        content = goods.getPrice() + "|" + goodCountAdd + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                        if(activity.mTicketInfo.isFSTH()) {//负数退货
                            goodCountAdd = -(Math.abs(Double.valueOf(goods.getSaleCount())) + 1);
//                            content = goods.getPrice() + "|" + (-goodCountAdd) + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                        }

                        QueryGoodParam param = new QueryGoodParam();
                        param.setGoodsPrice(goods.getPrice());
                        param.setCount(goodCountAdd+"");
                        param.setBarcode(goods.getBarcode());
                        param.setGoodsGuid(goods.getGoodsGuid());
                        param.setStamp(goods.getStamp());
                        activity.mSalePresenterImpl.queryGoods(param, activity.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                        break;
                    case R.id.img_sale_goods_cut:  //减商品
                        if (Math.abs(Double.valueOf(goods.getSaleCount())) > 1){
                            Double goodCountCut = Double.valueOf(goods.getSaleCount())-1;
//                            content = goods.getPrice() + "|" + goodCountCut + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                            if(activity.mTicketInfo.isFSTH()){//负数退货
                                goodCountCut = -(Math.abs(Double.valueOf(goods.getSaleCount())) - 1);
//                                content = goods.getPrice() + "|" + (-goodCountCut) + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                            }
                            if(goodCountCut == 0){
                                delectGood(goods);
                            }else{
                                QueryGoodParam paramCut = new QueryGoodParam();
                                paramCut.setGoodsPrice(goods.getPrice());
                                paramCut.setCount(goodCountCut+"");
                                paramCut.setBarcode(goods.getBarcode());
                                paramCut.setGoodsGuid(goods.getGoodsGuid());
                                paramCut.setStamp(goods.getStamp());
                                activity.mSalePresenterImpl.queryGoods(paramCut, activity.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                            }
                        }else {
                            delectGood(goods);
                        }
                        break;
                    case R.id.img_sale_goods_delect:  //删除商品
                        delectGood(goods);
                        break;
                    case R.id.img_sale_goods_discountFun:  //前台折扣
                         PermissionsUtils.checkPermission(null, activity, PermissionsUtils.SPZK, new PermissionsUtils.PermissionListener() {
                            @Override
                            public void onPermissionSuccess(MangerCardData mangerCardData, int flag) {
                                showFrontDiscountDialog(goods);
                            }

                            @Override
                            public void onPermissionFaild(String msg) {
                                ToastUtils.showMsg(msg);
                            }
                        });
                        break;
                    case R.id.tv_sale_goods_salecount://输入商品数量
                        InputNumberDialogCommon dialog = InputNumberDialogCommon.getInputNumberDialogCommon(activity, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
                            @Override
                            public void InputDialogOnSubmitClick(String content) {
                                try{
                                    Double goodStr = Double.parseDouble(content);
//                                    String goodCountStr = goods.getPrice() + "|" + content + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                                    QueryGoodParam paramInput = new QueryGoodParam();
                                    paramInput.setGoodsPrice(goods.getPrice());
                                    if(activity.mTicketInfo.isFSTH()) {//负数退货
                                        paramInput.setCount("-"+goodStr+"");
                                    }else {
                                        paramInput.setCount(goodStr + "");
                                    }
                                    paramInput.setBarcode(goods.getBarcode());
                                    paramInput.setGoodsGuid(goods.getGoodsGuid());
                                    activity.mSalePresenterImpl.queryGoods(paramInput, activity.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                                }catch (Exception e){
                                    ToastUtils.show("请输入正确的商品数量！");
                                }
                            }
                        });
                        dialog.setIsCanInputPoint(true);
                        dialog.setTitle("商品数量");
                        dialog.setContent("请输入商品数量");
                        dialog.setEtHint("请输入商品数量");
                        dialog.showDialog(false);
                        break;
                        default:
                            break;
                }

            }
        };

        /**
         * 点击输入商品数量
         */
        tvCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

//        etCount.setOnEditorActionListener(new TextView.OnEditorActionListener() {  //输入商品数量
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (TextUtils.isEmpty(etCount.getText().toString()))
//                    return false;
//                if (etCount.getText().toString().trim().contains("."))
//                {
//                    String content = goods.getPrice() + "|" + etCount.getText().toString().trim() + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
//                    activity.mSalePresenterImpl.queryGoods(content, activity.mTicketInfo);
//                }else {
//                    double saleCount = Integer.valueOf(etCount.getText().toString());
//                    if(saleCount ==0){
//                        saleCount = 1;
//                    }
//                    String content = goods.getPrice() + "|" + saleCount + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
//                    activity.mSalePresenterImpl.queryGoods(content, activity.mTicketInfo);
//
//                }
//                return false;
//            }
//        });

        imgAdd.setOnClickListener(itemListener);
        imgCut.setOnClickListener(itemListener);
        btnDelete.setOnClickListener(itemListener);
        btnDiscount.setOnClickListener(itemListener);
        tvCount.setOnClickListener(itemListener);
    }

    private void delectGood(final Goods goods) {
        SaleUtil.showInfoDialog(activity,
                ConstantString.DIALOG_MAIN_SUSPEND_ORDER_FAIL_TITLE,
                ConstantString.DIALOG_MAIN_DELECT_GOOD_MESSAGE,
                new OnDialogListener() {
                    @Override
                    public void onClick(int flag) {
                        if (flag == DialogConstant.DIALOG_BTN_SURE) {
                            QueryGoodParam param = new QueryGoodParam();
                            param.setGoodsPrice(goods.getPrice());
                            param.setCount("0");
                            param.setBarcode(goods.getBarcode());
                            param.setGoodsGuid(goods.getGoodsGuid());
                            param.setStamp(goods.getStamp());
//                            String content2 = goods.getPrice() + "|" + "0" + "|" + goods.getBarCode() + "|" + goods.getGoodsGuid();
                            activity.mSalePresenterImpl.queryGoods(param, activity.mTicketInfo, CommonUtils.isNullOrEmpty(goods.getTicktInx())? 0:Integer.parseInt(goods.getTicktInx()));
                        }
                    }
                }
        );
    }

    /**
     * 前台折扣展示
     * @param goods
     */
    private void showFrontDiscountDialog(final Goods goods) {
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_goods_frontdiscount, null);
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title_name);
        final SelfNumKeyView sf_containt = view.findViewById(R.id.member_soft_keyboard);

        tvTitle.setText("单品折扣");
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); //textview的drawableRight

        RadioButton rb_zkl = view.findViewById(R.id.rb_frontDiscount_zkl);//折扣率
        final RadioButton rb_zke = view.findViewById(R.id.rb_frontDiscount_zke);//折扣额
        TextView tv_payMoney = view.findViewById(R.id.tv_frontDiscount_payMoney);//应付金额
        final TextView tv_actuallyMoney = view.findViewById(R.id.tv_frontDiscount_actuallyMoney);//实付金额
        final TextView tv_discountType = view.findViewById(R.id.tv_zkType_name);//折扣名称
        final ImageView iv_discountRate = view.findViewById(R.id.iv_discountRate);//折扣率图片
        final EditText etDiscountRate = view.findViewById(R.id.et_frontDiscount_discountRate);//et折扣率
        final TextView tvDiscountRate = view.findViewById(R.id.tv_frontDiscount_discountRate);//et折扣率
        Button btnSure = view.findViewById(R.id.btn_frontDiscount_ok);//确定
        Button btnCancel = view.findViewById(R.id.btn_frontDiscount_cancel);//退出

        tv_payMoney.setText("￥"+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney()))+"");
        tv_actuallyMoney.setText("￥"+MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(goods.getSaleMoney()))+"");

        rb_zke.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_discountType.setText("折扣金额");
                iv_discountRate.setVisibility(View.GONE);

            }
        });

        rb_zkl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_discountType.setText("折  扣  率");
                iv_discountRate.setVisibility(View.VISIBLE);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });

        etDiscountRate.setFocusable(false);
        sf_containt.setEnterReceptor(etDiscountRate);
        sf_containt.setIsCanInputPoint(true);
        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {
                int zkje = 0;
                if(rb_zke.isChecked()){//折扣额
                    if(calculateFront(goods,1,num)!=null){
                        String actuallyMoney = MoneyUtils.getMabMoneyString(MoneyUtils.getSubtractMoneyOne(goods.getSaleMoney(),calculateFront(goods,1,num)).toString());
                        tv_actuallyMoney.setText("￥"+ actuallyMoney +"");
                        if(activity.mTicketInfo.isFSTH())
                            tv_actuallyMoney.setText("￥ -"+actuallyMoney);
                    }
                }else{//折扣率
                    if(calculateFront(goods,0,num)!=null){
                        String actuallyMoney = MoneyUtils.getMabMoneyString(MoneyUtils.getSubtractMoneyOne(goods.getSaleMoney(),calculateFront(goods,0,num)).toString());
                        tv_actuallyMoney.setText("￥"+ actuallyMoney +"");
                        if(activity.mTicketInfo.isFSTH())
                            tv_actuallyMoney.setText("￥ -"+actuallyMoney);
                    }
                }


            }
        });

        etDiscountRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtils.hideSoftInputButWithSelection(etDiscountRate,activity);
                etDiscountRate.setFocusable(true);
                etDiscountRate.setFocusableInTouchMode(true);
                etDiscountRate.requestFocus();
            }
        });

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                int disType =0;
                String discountInputContext = etDiscountRate.getText().toString();
                if(rb_zke.isChecked()){
                    disType =1;
                    if(activity.mTicketInfo.isFSTH())
                        discountInputContext = "-"+discountInputContext;
                }else{
                    if(etDiscountRate.getText()!=null&&!"".equals(etDiscountRate.getText()+"")) {
                        double tempDiscountRate = Double.valueOf(etDiscountRate.getText().toString()) / 10;
                        LogUtils.d("折扣率为：" + tempDiscountRate);//服务端定义
                        discountInputContext = tempDiscountRate + "";
                    }
                }
                if(calculateFront(goods,disType,etDiscountRate.getText().toString()) !=null)
                    activity.mSalePresenterImpl.frontDiscount(disType+"",discountInputContext,goods,activity.mTicketInfo.getOrderNo(),true);

            }
        });

        AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
        dialog.setView(view).setCancelable(false).create();
        mDialog = dialog.show();
    }

    /**
     *  前台折扣请求和判断
     * @param goods  商品列表
     * @param disType  0是折扣率 1是折扣金额
     * @param discount  折扣金额或者折扣率
     */
    private String calculateFront(Goods goods,int disType,String discount){
        String zkje = "0";
        if (TextUtils.isEmpty(discount)||discount == null){
            return null;
        }
        if(disType == 0){//折扣率
            double tempDiscountRate = Double.valueOf(discount)/100;
            if (tempDiscountRate <= 0 || tempDiscountRate >= 1) {
                ToastUtils.showMsg("请输入正确折扣率", 0);
                return null;
            }
            zkje = new DecimalFormat("0.00").format(Double.parseDouble(goods.getSaleMoney()) * (1 - tempDiscountRate)) +"";
        }else {
            int tempDiscount = MoneyUtils.getMoneyInt(discount);
            int goodSumMoney = Math.abs(MoneyUtils.getMoneyInt(goods.getSaleMoney()));
            if(tempDiscount>goodSumMoney){
                ToastUtils.showMsg("折扣金额不能大于销售金额",0);
                return null;
            }
            zkje =discount;
        }
        return zkje;
    }



}
